package com.web.app.common.support;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;

public class ConnectionManager {

	private static BasicDataSource dataSource = null;
	
	private ConnectionManager() {}

	private static BasicDataSource getDataSource() throws IOException {
		if (dataSource == null) {
			Properties prop = new Properties();
			prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties"));

			dataSource = new BasicDataSource();
			dataSource.setDriverClassName(prop.getProperty("jdbc.driverClassName"));
			dataSource.setUrl(prop.getProperty("jdbc.url"));
			dataSource.setUsername(prop.getProperty("jdbc.username"));
			dataSource.setPassword(prop.getProperty("jdbc.password"));
			dataSource.setInitialSize(Integer.parseInt(prop.getProperty("jdbc.initialSize")));
			dataSource.setMaxActive(Integer.parseInt(prop.getProperty("jdbc.maxActive")));
			dataSource.setMinIdle(Integer.parseInt(prop.getProperty("jdbc.minIdle")));
			dataSource.setMaxIdle(Integer.parseInt(prop.getProperty("jdbc.maxIdle")));
		}

		return dataSource;
	}

	public static Connection getConnection() throws IOException, SQLException {
		return getDataSource().getConnection();
	}

	public static Connection getConnection(String username, String password) throws IOException, SQLException {
		return getDataSource().getConnection(username, password);
	}

	public static Connection getConnection(String url, String username, String password) throws IOException,
	        SQLException {
		BasicDataSource dataSource = getDataSource();

		dataSource.setUrl(url);
		dataSource.setUsername(username);
		dataSource.setPassword(password);

		return dataSource.getConnection();
	}

	public static Connection getConnection(String driverClassName, String url, String username, String password)
	        throws IOException, SQLException {
		BasicDataSource dataSource = getDataSource();

		dataSource.setDriverClassName(driverClassName);
		dataSource.setUrl(url);
		dataSource.setUsername(username);
		dataSource.setPassword(password);

		return dataSource.getConnection();
	}

}
